package comgutianyu.qihangjiaoyu.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import comgutianyu.qihangjiaoyu.R;
import comgutianyu.qihangjiaoyu.db.UserDao;
import comgutianyu.qihangjiaoyu.model.User;

public class RegisterActivity extends AppCompatActivity {
    private EditText etNickname, etUsername, etPhone, etPassword;
    private RadioGroup rgGender;
    private Button btnRegister;
    private ImageButton btnTogglePassword;
    private boolean isPasswordVisible = false;
    private UserDao userDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        userDao = new UserDao(this);
        initViews();
        setListeners();
    }

    private void initViews() {
        etNickname = findViewById(R.id.etNickname);
        etUsername = findViewById(R.id.etUsername);
        etPhone = findViewById(R.id.etPhone);
        etPassword = findViewById(R.id.etPassword);
        rgGender = findViewById(R.id.rgGender);
        btnRegister = findViewById(R.id.btnRegister);
        btnTogglePassword = findViewById(R.id.btnTogglePassword);

        ImageButton btnBack = findViewById(R.id.btnBack);
        btnBack.setOnClickListener(v -> finish());
    }

    private void setListeners() {
        btnRegister.setOnClickListener(v -> attemptRegister());
        
        btnTogglePassword.setOnClickListener(v -> togglePasswordVisibility());
    }

    private void togglePasswordVisibility() {
        if (isPasswordVisible) {
            etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            btnTogglePassword.setImageResource(R.drawable.ic_visibility_off);
        } else {
            etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            btnTogglePassword.setImageResource(R.drawable.ic_visibility);
        }
        isPasswordVisible = !isPasswordVisible;
        etPassword.setSelection(etPassword.getText().length());
    }

    private void attemptRegister() {
        String nickname = etNickname.getText().toString().trim();
        String username = etUsername.getText().toString().trim();
        String phone = etPhone.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String gender = rgGender.getCheckedRadioButtonId() == R.id.rbMale ? "男" : "女";

        // 验证输入
        if (nickname.isEmpty()) {
            etNickname.setError("请输入昵称");
            return;
        }

        if (!isValidUsername(username)) {
            etUsername.setError("用户名必须是4-16位字母、数字或下划线");
            return;
        }

        if (!isValidPhoneNumber(phone)) {
            etPhone.setError("请输入有效的手机号");
            return;
        }

        if (password.isEmpty()) {
            etPassword.setError("请输入密码");
            return;
        }

        // 检查用户名和手机号是否已存在
        if (userDao.isUsernameExists(username)) {
            etUsername.setError("该用户名已被使用");
            return;
        }

        if (userDao.getUserByPhone(phone) != null) {
            etPhone.setError("该手机号已被注册");
            return;
        }

        // 创建新用户
        User newUser = new User(nickname, username, phone, password, gender, "未设置");
        newUser.setAvatarPath("default_avatar");

        // 保存用户信息
        long result = userDao.insertUser(newUser);
        if (result > 0) {
            // 注册成功，自动登录
            getSharedPreferences("user_prefs", MODE_PRIVATE)
                    .edit()
                    .putBoolean("is_logged_in", true)
                    .putString("current_phone", phone)
                    .apply();

            Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
            
            // 修改跳转逻辑
            Intent intent = new Intent(this, PersonalInfoActivity.class);
            // 清除任务栈中的所有Activity，并创建新的任务栈
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            finish();
        } else {
            Toast.makeText(this, "注册失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    private boolean isValidUsername(String username) {
        return username.matches("^[a-zA-Z0-9_]{4,16}$");
    }

    private boolean isValidPhoneNumber(String phone) {
        return phone.matches("^1[3-9]\\d{9}$");
    }
} 